package Homework3VideoStore;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class VideoStore
{
	private int sales = 0;
	private int currentDay = 1;
	private List<Customer> customerList;
	private List<Video> videoList;
	private List<Rental> records;
	private List<Rental> rentals;
	
	private Random randGen;
	
	public VideoStore()
	{
		customerList = new ArrayList<Customer>();
		videoList = new ArrayList<Video>();
		records = new ArrayList<Rental>();
		rentals = new ArrayList<Rental>();
		randGen = new Random();
	}
	
	public void addVideo(Video video)
	{
		videoList.add(video);
	}
	
	public void addCustomer(Customer customer)
	{
		customerList.add(customer);
	}
	
	public void nextDay()
	{
		currentDay++;
	}

	public void dailyRentals()
	{		
		for(int i = 0; i < customerList.size(); i++)
		{
			// short circuit if 0 videos in store
			if(videoList.size() < 1)
				return;
			
			Customer customer = customerList.get(i);
			if(customer.willComeIn() && customer.willRent(videoList.size()))
			{
				int numVids = customer.numberOfVideosToRent();
				if (numVids > videoList.size())
					numVids = videoList.size();
				
				List<Video> videosRented = new ArrayList<Video>();
				
				for(int j = 0; j < numVids; j++)
				{
					int video = randGen.nextInt(videoList.size());
					videosRented.add(videoList.get(video));
					videoList.remove(video);
				}
				
				Rental rental = customer.RentVideos(videosRented, currentDay);
				sales += rental.calculatePrice();
				records.add(rental);
				rentals.add(rental);
			}
		}
	}
	
	public void nightlyReturns()
	{
		// loop through all customers
		for(Customer customer : customerList)
		{
			// find what returns the customers have
			List<Rental> returns = customer.ReturnVideos(currentDay);
			
			for(Rental returnRental : returns)
			{
				// get the videos in the rental and return them to the videoList
				List<Video> returnVideos = returnRental.getVideosInRental();
				
				for(Video video : returnVideos)
				{
					videoList.add(video);
				}
				
				// remove return rental from existing rental list
				for(Rental rental : rentals)
				{
					if(rental.equals(returnRental))
					{
						rentals.remove(rental);
						break;
					}
				}
			}
		}
	}
	
	public void printSummary()
	{
		System.out.println("Total number of videos in store: " + videoList.size() + "\n");
		System.out.println("Videos:\n");
		for(Video video : videoList)
			System.out.println("\t" + video.toString());
		System.out.println("\nAmount of revenue: $" + sales + "\n");
		System.out.println("Completed rentals: " + records.size() + "\n");
		for(Rental rental : records)
			System.out.println(rental.toString());
		System.out.println("Active rentals: " + rentals.size() + "\n");
		for(Rental rental : rentals)
			System.out.println(rental.toString());
	}
}
